<!--
 * @Author: ZAL 2177624751@qq.com
 * @Date: 2025-03-31 16:43:41
 * @LastEditors: ZAL 2177624751@qq.com
 * @LastEditTime: 2025-03-31 16:06:38
 * @FilePath: \shop_app_vue3\pages\user\components\mapSelectAddress.vue
 * @Description: 地图选择地址页面
-->
<template>
  <view class="map-container">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="nav-title">选择地址</view>
    </view>

    <!-- 地图区域 -->
    <view class="map-wrapper">
      <map
        id="myMap"
        class="map"
        :latitude="latitude"
        :longitude="longitude"
        :markers="markers"
        :scale="16"
        show-location
        @regionchange="onRegionChange"
        @tap="onMapTap"
      >
        <!-- 中心点标记 -->
        <cover-image
          class="center-marker"
          src="/static/images/location-pin.png"
        ></cover-image>
      </map>
    </view>

    <!-- 地址信息表单 -->
    <view class="address-form">
      <view class="form-header">
        <text class="current-location">当前位置</text>
        <text class="location-text">{{ currentAddress }}</text>
      </view>

      <view class="form-content">
        <u-form :model="addressForm" ref="uForm">
          <u-form-item label="收货人" required>
            <u-input
              v-model="addressForm.name"
              placeholder="请输入收货人姓名"
              :border="false"
            ></u-input>
          </u-form-item>
          
          <u-form-item label="联系电话" required>
            <u-input
              v-model="addressForm.phone"
              placeholder="请输入联系电话"
              type="number"
              :border="false"
            ></u-input>
          </u-form-item>

          <u-form-item label="详细地址" required>
            <u-input
              v-model="addressForm.detail"
              placeholder="请输入详细地址，如：1号楼1单元101室"
              type="textarea"
              :border="false"
            ></u-input>
          </u-form-item>
        </u-form>
      </view>

      <!-- 设为默认地址开关 -->
      <view class="default-switch">
        <text>设为默认地址</text>
        <u-switch
          v-model="addressForm.isDefault"
          activeColor="#ff8800"
          size="28"
        ></u-switch>
      </view>

      <view class="default-tip">
        <text>设为默认地址后，下次下单会优先使用该地址</text>
      </view>
    </view>

    <!-- 底部按钮 -->
    <view class="footer">
      <u-button
        type="primary"
        color="#ff8800"
        @click="handleSubmit"
        :loading="loading"
      >保存地址</u-button>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'

const latitude = ref(39.909)
const longitude = ref(116.397)
const markers = ref([])
const currentAddress = ref('正在获取位置...')
const loading = ref(false)
const mapContext = ref(null)

const addressForm = ref({
  name: '',
  phone: '',
  detail: '',
  isDefault: false
})

// 初始化地图上下文
const initMapContext = () => {
  mapContext.value = uni.createMapContext('myMap')
}

// 获取当前位置
const getCurrentLocation = () => {
  uni.getLocation({
    type: 'gcj02',
    success: (res) => {
      latitude.value = res.latitude
      longitude.value = res.longitude
      updateMarker(res.latitude, res.longitude)
      getAddressFromLocation(res.latitude, res.longitude)
    },
    fail: (err) => {
      console.error('获取位置失败：', err)
      uni.showToast({
        title: '获取位置失败',
        icon: 'none'
      })
    }
  })
}

// 更新地图标记
const updateMarker = (lat, lng) => {
  markers.value = [{
    id: 1,
    latitude: lat,
    longitude: lng,
    iconPath: '/static/images/location-pin.png',
    width: 32,
    height: 32
  }]
}

// 地图区域改变事件
const onRegionChange = (e) => {
  if (e.type === 'end' && e.causedBy === 'drag') {
    // 获取地图中心点位置
    mapContext.value?.getCenterLocation({
      success: (res) => {
        latitude.value = res.latitude
        longitude.value = res.longitude
        updateMarker(res.latitude, res.longitude)
        getAddressFromLocation(res.latitude, res.longitude)
      }
    })
  }
}

// 点击地图事件
const onMapTap = (e) => {
  const { latitude: lat, longitude: lng } = e.detail
  latitude.value = lat
  longitude.value = lng
  updateMarker(lat, lng)
  getAddressFromLocation(lat, lng)
}

// 根据经纬度获取地址信息
const getAddressFromLocation = (lat, lng) => {
  uni.chooseLocation({
    latitude: lat,
    longitude: lng,
    success: (res) => {
      currentAddress.value = res.address
      // 可以将位置名称添加到详细地址中
      if (res.name) {
        addressForm.value.detail = res.name
      }
    },
    fail: () => {
      currentAddress.value = '获取地址失败'
    }
  })
}

// 提交表单
const handleSubmit = () => {
  if (!currentAddress.value) {
    uni.showToast({
      title: '请选择位置',
      icon: 'none'
    })
    return
  }

  if (!addressForm.value.name) {
    uni.showToast({
      title: '请输入收货人姓名',
      icon: 'none'
    })
    return
  }

  if (!addressForm.value.phone) {
    uni.showToast({
      title: '请输入联系电话',
      icon: 'none'
    })
    return
  }

  if (!addressForm.value.detail) {
    uni.showToast({
      title: '请输入详细地址',
      icon: 'none'
    })
    return
  }

  // 返回地址信息给上一页
  const addressInfo = {
    latitude: latitude.value,
    longitude: longitude.value,
    address: currentAddress.value,
    name: addressForm.value.name,
    phone: addressForm.value.phone,
    detail: addressForm.value.detail,
    isDefault: addressForm.value.isDefault
  }

  uni.$emit('addressSelected', addressInfo)
  uni.navigateBack()
}

onMounted(() => {
  initMapContext()
  getCurrentLocation()
})
</script>

<style lang="scss" scoped>
.map-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

.nav-bar {
  background-color: #fff;
  height: 88rpx;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  position: sticky;
  top: 0;
  z-index: 100;
  
  .nav-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
  }
}

.map-wrapper {
  position: relative;
  height: 45vh;
  
  .map {
    width: 100%;
    height: 100%;
  }
  
  .center-marker {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    width: 32px;
    height: 32px;
    z-index: 10;
  }
}

.address-form {
  flex: 1;
  background-color: #fff;
  border-radius: 24rpx 24rpx 0 0;
  margin-top: -24rpx;
  padding: 30rpx;
  position: relative;
  z-index: 20;
  
  .form-header {
    margin-bottom: 30rpx;
    
    .current-location {
      font-size: 28rpx;
      color: #999;
      margin-bottom: 10rpx;
      display: block;
    }
    
    .location-text {
      font-size: 32rpx;
      color: #333;
      font-weight: bold;
    }
  }
  
  .form-content {
    margin-bottom: 30rpx;
    
    :deep(.u-form-item) {
      padding: 20rpx 0;
    }
    
    :deep(.u-input) {
      margin-left: 20rpx;
    }
  }
  
  .default-switch {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx 0;
    border-top: 2rpx solid #f5f5f5;
    
    text {
      font-size: 28rpx;
      color: #333;
    }
  }
  
  .default-tip {
    font-size: 24rpx;
    color: #999;
    margin-top: 10rpx;
  }
}

.footer {
  padding: 20rpx 30rpx;
  background-color: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  
  :deep(.u-button) {
    height: 88rpx;
    border-radius: 44rpx;
    font-size: 32rpx;
    
    &:active {
      transform: scale(0.98);
    }
  }
}
</style>